package com.ts.camera2

import android.util.Size
import android.view.TextureView
import android.view.ViewGroup
import androidx.camera.core.CameraX
import androidx.camera.core.Preview
import androidx.camera.core.PreviewConfig

import androidx.lifecycle.LifecycleOwner

class CameraXUtil(life: LifecycleOwner, display: TextureView) : Preview.OnPreviewOutputUpdateListener {

    var textureView:TextureView?=null;

    init {
        var previewConfig= PreviewConfig.Builder()
            .setTargetResolution(Size(480,640)).build()
        var preview= Preview(previewConfig)
        preview.setOnPreviewOutputUpdateListener(this)
        CameraX.bindToLifecycle(life, preview)
    }

    override fun onUpdated(output: Preview.PreviewOutput?) {
//        output.surfaceTexture
        var surfaceTexture=output?.surfaceTexture;
        if (textureView?.isAvailable() == true) {
            // 当切换摄像头时，会报错
            val parent = textureView?.parent as ViewGroup
            parent.removeView(textureView)
            parent.addView(textureView, 0)
            parent.requestLayout()
            surfaceTexture?.let { textureView?.setSurfaceTexture(it) }
        }
    }
}